//
//  Communication.m
//  TinyFortune
//
//  Created by lc on 16/6/3.
//  Copyright © 2016年 lc. All rights reserved.
//

//文本信息相关
#import "Communication.h"
#import "LeftCell.h"
#import "RightCell.h"

#import "comModel.h"
#import "AVFile +  getDictionary.h"
#import "emojiView.h"
//声音消息相关
#import "audioLeft.h"
#import "rightAudioCell.h"

NSString *const leftCellIdentifier = @"left";
NSString *const rightCellIdentifier = @"right";
NSString *const leftAudio = @"leftAudio";
NSString *const rightAudio = @"rightAudio";


@interface Communication ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,AVIMClientDelegate>{
    UIView *_tView;//下面的聊天栏
    emojiView *_emojiKeyboard;//自定制表情键盘
    UIButton *_talkButton;//麦克风按钮
    UIView *_microPhoneView;//麦克风页面
    NSTimeInterval _micTime;//录音的时长
    NSString *_timeString;//录音的时间，作为存储的地址
}

//tableView三件套
@property (nonatomic,strong)UITableView *comTableView;
@property (nonatomic,strong)UITextView *textView;//聊天界面输入文本框


//=====================音频相关===========================
/**麦克风照片*/
@property (nonatomic,strong)UIImageView *microImageView;
/**声音大小照片组*/
@property (nonatomic,strong)UIImageView *soundImageView;
/**录音器*/
@property (strong,nonatomic)AVAudioRecorder *recoder;
/**播放器*/
@property (nonatomic,strong)AVAudioPlayer *player;
/**定时器*/
@property (nonatomic,strong)NSTimer *timer;
/**图片组*/
@property (nonatomic,strong)NSMutableArray *volumImages;
@property (nonatomic,assign)double lowPassResults;

@property (nonatomic,strong)NSDictionary *recorderSettingsDict;
/**录音名字*/
@property (nonatomic,copy)NSString *playName;


@end

@implementation Communication
#pragma mark -懒加载
- (DatabaseManager *)DBmanager{
    if (!_DBmanager) {
        _DBmanager = [DatabaseManager defaultManager];
    }
    return _DBmanager;
}
- (NSMutableArray *)currentUserArray{
    if (!_currentUserArray) {
        _currentUserArray = [NSMutableArray new];
    }
    return _currentUserArray;
}

#pragma mark -点击事件
- (void)cancel{
    [self.navigationController popViewControllerAnimated:YES];
   // [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)rightGo{
    [self cancel];
}
#pragma mark -界面搭建
- (void)createUI{
    //实例化导航条
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
    [self.navigationItem setLeftBarButtonItem:leftBar];
    self.navigationController.navigationBar.translucent = NO ;
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:86/255.0f green:202/255.0f blue:255/255.0f alpha:0.5]];
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [self setTitle:@"聊天"];
    //添加滑动手势
    UISwipeGestureRecognizer *rightSwip = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(rightGo)];
    [self.view addGestureRecognizer:rightSwip];
    [rightSwip setDirection:UISwipeGestureRecognizerDirectionRight];
    
    
    //实例化tableView
    //这里减去64我感觉应该是算了导航栏，反正不减又不对
    _comTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, LC_WIDTH, self.view.frame.size.height - 44 - 64)];
    [self.view addSubview:_comTableView];
    [_comTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    _comTableView.delegate = self ;
    _comTableView.dataSource = self ;
    _comTableView.backgroundColor = [UIColor colorWithRed:239/255.0f green:239/255.0f blue:244/255.0f alpha:1];
    //注册单元格
    [_comTableView registerNib:[UINib nibWithNibName:@"LeftCell" bundle:nil] forCellReuseIdentifier:leftCellIdentifier];
    [_comTableView registerNib:[UINib nibWithNibName:@"RightCell" bundle:nil] forCellReuseIdentifier:rightCellIdentifier];
    [_comTableView registerNib:[UINib nibWithNibName:@"audioLeft" bundle:nil] forCellReuseIdentifier:leftAudio];
    [_comTableView registerNib:[UINib nibWithNibName:@"rightAudioCell" bundle:nil] forCellReuseIdentifier:rightAudio];
    //实例化文本输入框
    [self createTextView];
    //实例化emoji表情
    _emojiKeyboard = [[emojiView alloc]init];
    //正向传值
    _emojiKeyboard.textView = _textView;
    
    
}
#pragma mark - 按钮点击事件
//替换表情键盘
- (void)face:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected == NO) {
        _textView.inputView = nil;
        [_textView reloadInputViews];
        [_textView becomeFirstResponder];
        
    }else{
        _textView.inputView = _emojiKeyboard;
        [_textView reloadInputViews];
        [_textView becomeFirstResponder];
        
    }
    
}
- (void)talking:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected == NO) {
        _textView.alpha = 1 ;
        _talkButton.alpha = 0 ;
        _textView.inputView = nil;
        [_textView reloadInputViews];
        [_textView becomeFirstResponder];
    }else{
        _textView.alpha = 0;
        _talkButton.alpha = 1;
        [_textView resignFirstResponder];
    }
}
//说话按钮
- (void)pressTalk:(UIButton *)sender {
    sender.selected = YES ;
    //拿到沙河路径
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    //我需要让声音有一个唯一性,所以以时间作为名字
    NSDate *date = [NSDate new];
    NSDateFormatter *formatter = [NSDateFormatter new];
    formatter.dateFormat = @"MM-dd-HH-mm";
    _timeString = [formatter stringFromDate:date];
    
    _playName = [NSString stringWithFormat:@"%@/%@play.acc",docDir,_timeString];
    NSLog(@"%@",_playName);
    
    //按下录音
    if ([self canRecord]) {
        _microPhoneView.alpha = 1 ;
        NSError *error = nil;
        //必须真机上测试,模拟器上可能会崩溃
        _recoder = [[AVAudioRecorder alloc] initWithURL:[NSURL URLWithString:_playName] settings:_recorderSettingsDict error:&error];
        
        if (_recoder) {
            _recoder.meteringEnabled = YES;
            [_recoder prepareToRecord];
            [_recoder record];
            
            //启动定时器
            _timer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(levelTimer:) userInfo:nil repeats:YES];
            
        } else
        {
            int errorCode = CFSwapInt32HostToBig ([error code]);
            NSLog(@"Error: %@ [%4.4s])" , [error localizedDescription], (char*)&errorCode);
            
        }
    }
}
- (void)upTalk:(UIButton *) sender{
    sender.selected = NO;
    
    
    
    //获取录音时长
    _micTime = _recoder.currentTime ;
    NSLog(@"录音时间%f",_micTime);
    //松开 结束录音
    _microPhoneView.alpha = 0 ;
    //录音停止
    [_recoder stop];
    _recoder = nil;
    //结束定时器
    [_timer invalidate];
    _timer = nil;
    //图片重置
    _microImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:0]];
    //发送音频
    [self sendAVAudioMessage];
}
#pragma mark - 实例化麦克风
- (void)createMicro{
    //实例化麦克风的黑框框
    _microPhoneView = [UIView new];
    [self.view addSubview:_microPhoneView];
    _microPhoneView.translatesAutoresizingMaskIntoConstraints = NO;
    __weak typeof(self)weakSelf = self ;
    CGFloat wOffset = (LC_WIDTH - 120 )/2.0f;
    CGFloat Hoffset = (LC_HEIGHT - 120 - 64 - 44)/2.0f;
    [_microPhoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@120);
        make.height.equalTo(@120);
        make.left.equalTo(weakSelf.view.mas_left).offset(wOffset);
        make.top.equalTo(weakSelf.view.mas_top).offset(Hoffset);
    }];
    _microPhoneView.layer.masksToBounds = YES ;
    _microPhoneView.layer.cornerRadius = 10 ;
    _microPhoneView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    //麦克风照片
    UIImageView *MiImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Micro"]];
    MiImageView.translatesAutoresizingMaskIntoConstraints = NO;
    [_microPhoneView addSubview:MiImageView];
    [MiImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_microPhoneView.mas_top).offset(20);
        make.left.equalTo(_microPhoneView.mas_left).offset(20);
        make.width.equalTo(@45);
        make.height.equalTo(@64);
    }];
    //音频照片组
    _soundImageView = [[ UIImageView alloc]init];
    _soundImageView.translatesAutoresizingMaskIntoConstraints = NO;
    [_microPhoneView addSubview:_soundImageView];
    [_soundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(MiImageView.mas_height);
        make.top.equalTo(MiImageView.mas_top);
        make.left.equalTo(MiImageView.mas_right).offset(10);
        make.width.equalTo(@20);
    }];
    
    
    
    
    //录音设置
    _recorderSettingsDict =[[NSDictionary alloc] initWithObjectsAndKeys:
                            [NSNumber numberWithInt:kAudioFormatMPEG4AAC],AVFormatIDKey,
                            //采样率
                            [NSNumber numberWithInt:1000.0],AVSampleRateKey,
                            //采样的通道数(我用了双向)
                            [NSNumber numberWithInt:2],AVNumberOfChannelsKey,
                            //采样位数
                            [NSNumber numberWithInt:8],AVLinearPCMBitDepthKey,
                            //大端还是小端，内存的组织方式
                            [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
                            //采样信号是整数还是浮点数
                            [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
                            nil];
    //音量图片数组
    _volumImages = [[NSMutableArray alloc]initWithObjects:@"RecordingSignal001",@"RecordingSignal002",@"RecordingSignal003",
                    @"RecordingSignal004", @"RecordingSignal005",@"RecordingSignal006",
                    @"RecordingSignal007",@"RecordingSignal008",   nil];
}
#pragma mark - 实例化文本输入框
- (void)createTextView{
    _tView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 44 - 64, LC_WIDTH, 44)];
    _tView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_tView];

    //语音按钮
    UIButton *yuyinButton = [UIButton new];
    [yuyinButton setImage:[UIImage imageNamed:@"yuyin"] forState:UIControlStateNormal];
    [yuyinButton setImage:[UIImage imageNamed:@"lightKeyboard"] forState:UIControlStateSelected];
    yuyinButton.translatesAutoresizingMaskIntoConstraints = NO;
    [_tView addSubview:yuyinButton];
    [yuyinButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_tView.mas_left).offset(5);
        make.top.equalTo(_tView.mas_top).offset(9);
        make.width.equalTo(@26);
        make.height.equalTo(@26);
    }];
    [yuyinButton addTarget:self action:@selector(talking:) forControlEvents:UIControlEventTouchDown];
    
    
//    //加号按钮
//    UIButton *addButton =[UIButton new];
//    [addButton setImage:[[UIImage imageNamed:@"jiahao"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]forState:UIControlStateNormal];
//    addButton.translatesAutoresizingMaskIntoConstraints = NO;
//    [_tView addSubview:addButton];
//    [addButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(_tView.mas_right).offset(0);
//        make.top.equalTo(_tView.mas_top).offset(9);
//        make.width.equalTo(@26);
//        make.height.equalTo(@26);
//    }];
//    [addButton addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchDown];
    //表情按钮
    UIButton *faceButton =[UIButton new];
    [faceButton setImage:[UIImage imageNamed:@"biaoqing"] forState:UIControlStateNormal];
    [faceButton setImage:[UIImage imageNamed:@"keyBoard"] forState:UIControlStateSelected];
    faceButton.translatesAutoresizingMaskIntoConstraints = NO;
    [_tView addSubview:faceButton];
    [faceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_tView.mas_right).offset(-10);
        make.top.equalTo(_tView.mas_top).offset(9);
        make.width.equalTo(@26);
        make.height.equalTo(@26);
    }];
    [faceButton addTarget:self action:@selector(face:) forControlEvents:UIControlEventTouchDown];
    
    //文本输入框
    _textView = [UITextView new];
    _textView.translatesAutoresizingMaskIntoConstraints = NO;
    [_tView addSubview:_textView];
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_tView.mas_top).offset(5);
        make.right.equalTo(faceButton.mas_left).offset(-5);
        make.left.equalTo(yuyinButton.mas_right).offset(5);
        make.height.equalTo(@34);
    }];
    
    _textView.layer.cornerRadius = 5;
    _textView.layer.masksToBounds = YES ;
    [_textView setReturnKeyType:UIReturnKeySend];
    _textView.backgroundColor = [UIColor colorWithRed:239/255.0f green:239/255.0f blue:244/255.0f alpha:1];
    _textView.delegate = self;
    
    //说话的一个按钮
    _talkButton = [UIButton new];
    _talkButton.translatesAutoresizingMaskIntoConstraints = NO;
    [_tView addSubview:_talkButton];
    [_talkButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_textView);
    }];
    [_talkButton setTitle:@"按住 说话" forState:UIControlStateNormal];
    [_talkButton setTitle:@"松开 发送" forState:UIControlStateSelected];
    [_talkButton addTarget:self action:@selector(pressTalk:) forControlEvents:UIControlEventTouchDown];
    [_talkButton addTarget:self action:@selector(upTalk:) forControlEvents:UIControlEventTouchUpInside];
    _talkButton.layer.cornerRadius = 5 ;
    _talkButton.layer.masksToBounds = YES ;
    _talkButton.backgroundColor = [UIColor colorWithRed:239/255.0f green:239/255.0f blue:244/255.0f alpha:1];
    _talkButton.alpha = 0 ;
}
#pragma mark -及时通信发送消息的实现
//MARK:发送音频消息
- (void)sendAVAudioMessage{
    AVUser *user = [AVUser currentUser];
    
    //==================获取头像========================
    AVFile *file = [user objectForKey:@"iconImage"];
    NSDictionary *dict = [AVFile fileWithDictionary:file];
    NSString *iconStr = dict[@"url"];
    
    
    
    AVFile *audioFile = [AVFile fileWithName:@"语音" contentsAtPath:_playName];
    [audioFile.metaData setObject:[NSString stringWithFormat:@"%.1lf''",_micTime] forKey:@"time"];
    AVIMAudioMessage *audioMessage =[AVIMAudioMessage messageWithText:@"听听语音" file:audioFile attributes:nil];
    
    __weak typeof(self)weakSelf = self ;
    if ([self.client conversationForId:self.conversation.conversationId]) {
        [self.conversation sendMessage:audioMessage callback:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                //如果成功了,就把这条小心加入数据源数组，然后再刷新tableView
                
                NSDictionary *tDic = @{
                                       @"iconImage":iconStr,
                                       @"text":_textView.text,
                                       @"userId":audioMessage.clientId,
                                       @"mediaType":@"-3",
                                       @"audioUrl":[NSString stringWithFormat:@"/%@play.acc",_timeString],
                                       @"time":[NSString stringWithFormat:@"%.1lf''",_micTime]
                                       };
                NSLog(@"字典的数据%@",tDic[@"time"]);
                NSLog(@"此时的数据%lf",_micTime);
                NSLog(@"");
                
                comModel *model = [[comModel alloc]initWithDict:tDic];
                //这个是数据源数组
                [weakSelf.currentUserArray addObject:model];
                //还要保存到本地数据库
                [weakSelf.DBmanager cretatTableFromClass:[comModel class]];
                [weakSelf.DBmanager cretatTableFromClass:[AVIMMessage class]];
                [weakSelf.DBmanager insertObject:model];
                [weakSelf.DBmanager insertObject:audioMessage];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //记得要判断此时数组有没有东西
                    if (self.currentUserArray.count > 0) {
                        //把信息插入在最下面
                        [weakSelf.comTableView beginUpdates];
                        NSMutableArray *indexPaths = [NSMutableArray new];
                        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentUserArray.count-1 inSection:0];
                        [indexPaths addObject:indexPath];
                        [weakSelf.comTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationBottom];
                        [weakSelf.comTableView endUpdates];
                        
                        
                        
                    }
                });
                NSLog(@"发送成功!");
                
            }else{
                //打印错误
                NSLog(@"%@",error.localizedDescription);
            }
        }];
    }else{
        //与恋人建立对话
        [self.client createConversationWithName:@"当前聊天" clientIds:@[[user objectForKey:@"lovers"]] callback:^(AVIMConversation *conversation, NSError *error) {
            //当前用户发送了一条消息给恋人
            [conversation sendMessage:audioMessage callback:^(BOOL succeeded, NSError *error) {
                self.conversation = conversation;
                if (succeeded) {
                    //如果成功了,就把这条小心加入数据源数组，然后再刷新tableView
                    
                    NSDictionary *tDic = @{
                                           @"iconImage":iconStr,
                                           @"text":_textView.text,
                                           @"userId":audioMessage.clientId,
                                           @"audioUrl":[NSString stringWithFormat:@"/%@play.acc",_timeString],
                                           @"mediaType":@"-3",
                                           @"time":[NSString stringWithFormat:@"%.1lf''",_micTime]
                                           };
                    comModel *model = [[comModel alloc]initWithDict:tDic];
                    
                    //这个是数据源数组
                    [weakSelf.currentUserArray addObject:model];
                    
                    [weakSelf.DBmanager cretatTableFromClass:[comModel class]];
                    [weakSelf.DBmanager cretatTableFromClass:[AVIMMessage class]];
                    [weakSelf.DBmanager insertObject:model];
                    [weakSelf.DBmanager insertObject:audioMessage];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (weakSelf.currentUserArray.count > 0) {
                            //把信息插入在最下面
                            [weakSelf.comTableView beginUpdates];
                            NSMutableArray *indexPaths = [NSMutableArray new];
                            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentUserArray.count-1 inSection:0];
                            [indexPaths addObject:indexPath];
                            [weakSelf.comTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationBottom];
                            [weakSelf.comTableView endUpdates];
                            //将tableView滚动到最下面
                            NSIndexPath *path = [NSIndexPath indexPathForRow:self.currentUserArray.count - 1 inSection:0];
                            [weakSelf.comTableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                            
                        }
                    });
                    NSLog(@"发送成功!");
                    
                }else{
                    //打印错误
                    NSLog(@"%@",error.localizedDescription);
                }
            }];
            
            
        }];
    }
    
}
//MARK:发送消息
- (void)sendMessage{
    AVUser *user = [AVUser currentUser];
    
    //==================获取头像========================
    AVFile *file = [user objectForKey:@"iconImage"];
    NSDictionary *dict = [AVFile fileWithDictionary:file];
    NSString *iconStr = dict[@"url"];
    
    AVIMTextMessage *myMessage = [AVIMTextMessage messageWithText:_textView.text attributes:nil];
    __weak typeof(self)weakSelf = self ;
    
    if ([self.client conversationForId:self.conversation.conversationId]) {
        [self.conversation sendMessage:myMessage callback:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                //如果成功了,就把这条小心加入数据源数组，然后再刷新tableView
                
                NSDictionary *tDic = @{
                                       @"iconImage":iconStr,
                                       @"text":_textView.text,
                                       @"mes":myMessage,
                                       @"userId":myMessage.clientId,
                                       @"mediaType":@"-1",
                                       @"audioUrl":@"aa",
                                       @"time":[NSString stringWithFormat:@"%.1lf''",_micTime]
                                       };
                NSLog(@"!!®%@",tDic[@"time"]);
                comModel *model = [[comModel alloc]initWithDict:tDic];
                
                //这个是数据源数组
                [weakSelf.currentUserArray addObject:model];
                //还要保存到本地数据库
                [weakSelf.DBmanager cretatTableFromClass:[comModel class]];
                [weakSelf.DBmanager cretatTableFromClass:[AVIMTypedMessage class]];
                [weakSelf.DBmanager insertObject:model];
                [weakSelf.DBmanager insertObject:myMessage];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //把信息插入在最下面
                    [weakSelf.comTableView beginUpdates];
                    NSMutableArray *indexPaths = [NSMutableArray new];
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentUserArray.count-1 inSection:0];
                    [indexPaths addObject:indexPath];
                    [weakSelf.comTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationBottom];
                    [weakSelf.comTableView endUpdates];
                    
                    
                });
                NSLog(@"发送成功!");
                
            }else{
                //打印错误
                NSLog(@"%@",error.localizedDescription);
            }
        }];
    }else{
        NSLog(@"%@",[user objectForKey:@"lovers"]);
        //与恋人建立对话
        [self.client createConversationWithName:@"当前聊天" clientIds:@[[user objectForKey:@"lovers"]] callback:^(AVIMConversation *conversation, NSError *error) {
            //当前用户发送了一条消息给恋人
            [conversation sendMessage:myMessage callback:^(BOOL succeeded, NSError *error) {
                self.conversation = conversation;
                if (succeeded) {
                    //如果成功了,就把这条小心加入数据源数组，然后再刷新tableView
                    
                    NSDictionary *tDic = @{
                                           @"iconImage":iconStr,
                                           @"text":_textView.text,
                                           @"userId":myMessage.clientId,
                                           @"audioUrl":@"aa",
                                           @"mediaType":@"-1",
                                           @"mes":myMessage,
                                           @"time":[NSString stringWithFormat:@"%.1lf''",_micTime]                             };
                    NSLog(@"!!®%@",tDic[@"time"]);
                    comModel *model = [[comModel alloc]initWithDict:tDic];
                    //这个是数据源数组
                    [weakSelf.currentUserArray addObject:model];
                    
                    [weakSelf.DBmanager cretatTableFromClass:[comModel class]];
                    [weakSelf.DBmanager cretatTableFromClass:[AVIMTypedMessage class]];
                    [weakSelf.DBmanager insertObject:model];
                    [weakSelf.DBmanager insertObject:myMessage];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        //把信息插入在最下面
                        [weakSelf.comTableView beginUpdates];
                        NSMutableArray *indexPaths = [NSMutableArray new];
                        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentUserArray.count-1 inSection:0];
                        [indexPaths addObject:indexPath];
                        [weakSelf.comTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationBottom];
                        [weakSelf.comTableView endUpdates];
                        //将tableView滚动到最下面
                        NSIndexPath *path = [NSIndexPath indexPathForRow:self.currentUserArray.count - 1 inSection:0];
                        [weakSelf.comTableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                        
                        
                    });
                    NSLog(@"发送成功!");
                    
                }else{
                    //打印错误
                    NSLog(@"%@",error.localizedDescription);
                }
            }];
            
            
        }];
    }
}
#pragma mark - 即时通许增加历史记录
- (void)loadHistory{
    
    [self.currentUserArray addObjectsFromArray:[self.DBmanager selectAllObjectFromClass:[comModel class]]];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.comTableView reloadData];
    })  ;
}

#pragma mark - AVIMClientDelegate
//MARK:接受消息回调函数
- (void)conversation:(AVIMConversation *)conversation didReceiveTypedMessage:(AVIMTypedMessage *)message{
    //这里要手动设置类型，坑爹
    NSString *strType;
    __weak typeof(self)weakSelf = self;
    if (message.mediaType == -1) {
        strType = @"-1";
        //正在通信人的ID
        NSString *loversPhoneNumber = [[AVUser currentUser]objectForKey:@"lovers"];
        AVQuery *query = [AVQuery queryWithClassName:@"_User"];
        [query whereKey:@"mobilePhoneNumber" equalTo:loversPhoneNumber];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            //==================获取头像========================
            AVUser *user = (AVUser *) objects.firstObject;
            AVFile *file =  [user objectForKey:@"iconImage"];
            NSDictionary *dict = [AVFile fileWithDictionary:file];
            NSDictionary *tDic = @{
                                   @"iconImage":dict[@"url"],
                                   @"text":message.text,
                                   @"userId":message.clientId,
                                   @"mediaType":strType,
                                   @"audioUrl":@"0",
                                   @"time":@"00"                             };
            
            comModel *model = [[comModel alloc]initWithDict:tDic];
            [weakSelf.currentUserArray addObject:model];
            [weakSelf.DBmanager insertObject:model];
            //还要保存到本地数据库
            
            [weakSelf.DBmanager  cretatTableFromClass:[comModel class]];
            [weakSelf.DBmanager cretatTableFromClass:[AVIMMessage class]];
            
            [weakSelf.DBmanager insertObject:message];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //把信息插入在最下面
                if (weakSelf.currentUserArray.count > 0) {
                    [weakSelf.comTableView beginUpdates];
                    NSMutableArray *indexPaths = [NSMutableArray new];
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentUserArray.count - 1 inSection:0];
                    [indexPaths addObject:indexPath];
                    [weakSelf.comTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationBottom];
                    [weakSelf.comTableView endUpdates];
                    //将tableView滚动到最下面
                    
                    NSIndexPath *path = [NSIndexPath indexPathForRow:self.currentUserArray.count-1  inSection:0];
                    [weakSelf.comTableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                    
                }
                
            });
            
        }];
        
        
    }else{
        strType = @"-3";
        //获取音频消息的字典
        NSDictionary *tDict = [AVFile fileWithDictionary:message.file];
        //找到音频的文件，获取文件源信息
        [AVFile getFileWithObjectId:tDict[@"objectId"] withBlock:^(AVFile *file, NSError *error) {
            NSDictionary *fileDict = [AVFile fileWithDictionary:file];
            //===========把音频下载下来，保存到本地==============
            NSURL *url = [[NSURL alloc]initWithString:fileDict[@"url"]];
            NSData *data = [NSData dataWithContentsOfURL:url];
            //将数据保存到指定位置
            NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            
            NSDate *date = [NSDate new];
            NSDateFormatter *formatter = [NSDateFormatter new];
            formatter.dateFormat = @"MM-dd-HH-mm";
            _timeString = [formatter stringFromDate:date];
            
        
            
            NSString *filePath = [NSString stringWithFormat:@"%@/%@play.acc",docDir,_timeString];
          
            [data writeToFile:filePath atomically:YES];
            
            
            
            //正在通信人的ID
            NSString *loversPhoneNumber = [[AVUser currentUser]objectForKey:@"lovers"];
            AVQuery *query = [AVQuery queryWithClassName:@"_User"];
            [query whereKey:@"mobilePhoneNumber" equalTo:loversPhoneNumber];
            [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                //==================获取头像========================
                AVUser *user = (AVUser *) objects.firstObject;
                AVFile *file =  [user objectForKey:@"iconImage"];
                NSDictionary *dict = [AVFile fileWithDictionary:file];
                NSLog(@"%@",fileDict);
                NSDictionary *tDic = @{
                                       @"iconImage":dict[@"url"],
                                       @"text":message.text,
                                       @"userId":message.clientId,
                                       @"mediaType":strType,
                                       @"audioUrl":[NSString stringWithFormat:@"/%@play.acc",_timeString],
                                       @"time":fileDict[@"metaData"][@"time"]                             };
                
                comModel *model = [[comModel alloc]initWithDict:tDic];
                [weakSelf.currentUserArray addObject:model];
                [weakSelf.DBmanager insertObject:model];
                //还要保存到本地数据库
                
                [weakSelf.DBmanager  cretatTableFromClass:[comModel class]];
                [weakSelf.DBmanager cretatTableFromClass:[AVIMMessage class]];
                
                [weakSelf.DBmanager insertObject:message];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    //把信息插入在最下面
                    if (weakSelf.currentUserArray.count > 0) {
                        [weakSelf.comTableView beginUpdates];
                        NSMutableArray *indexPaths = [NSMutableArray new];
                        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentUserArray.count - 1 inSection:0];
                        [indexPaths addObject:indexPath];
                        [weakSelf.comTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationBottom];
                        [weakSelf.comTableView endUpdates];
                        //将tableView滚动到最下面
                        
                        NSIndexPath *path = [NSIndexPath indexPathForRow:self.currentUserArray.count-1  inSection:0];
                        [weakSelf.comTableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                        
                    }
                    
                });
                
            }];
            
            
        }];
        
        
    }
    
    
}

#pragma mark -textView协议
- (void)textViewDidBeginEditing:(UITextView *)textView{
    textView.text = @"";
}
//输入完成之后显示,发送，保存到本地数据库
- (void)textViewDidEndEditing:(UITextView *)textView{
    [self sendMessage];
    
}
//当遇到换行是,默认发送
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
    }
    return YES;
}

#pragma mark -tableView协议


//动态确定每个cell的长度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    comModel *comModel = self.currentUserArray[indexPath.row];
    CGRect rect = [comModel.text boundingRectWithSize:CGSizeMake(LC_WIDTH - 150, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
    if (rect.size.height +25 > 70) {
        return rect.size.height +27;
    }else{
        return 70;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.currentUserArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    comModel *model = self.currentUserArray[indexPath.row];
    
    BOOL isMe = [self.client.clientId isEqualToString:model.userId];
    NSLog(@"%@",model);
    
    switch ([model.mediaType intValue]) {
            //此时是一般的text消息
        case -1:{
            //如果是自己发送的消息,调用leftCell
            if(!isMe){
                LeftCell *leftCell = [tableView dequeueReusableCellWithIdentifier:leftCellIdentifier forIndexPath:indexPath];
                leftCell.model  = self.currentUserArray[indexPath.row];
                leftCell.backgroundColor =[UIColor colorWithRed:239/255.0f green:239/255.0f blue:244/255.0f alpha:1];
                
                [leftCell setSelectionStyle:UITableViewCellSelectionStyleNone];
                return leftCell ;
            }
            //如果是收到的消息就以第二种格式
            else{
                RightCell *rightCell = [tableView dequeueReusableCellWithIdentifier:rightCellIdentifier forIndexPath:indexPath];
                rightCell.model = self.currentUserArray[indexPath.row];
                rightCell.backgroundColor = [UIColor colorWithRed:239/255.0f green:239/255.0f blue:244/255.0f alpha:1];
                
                [rightCell setSelectionStyle:UITableViewCellSelectionStyleNone];
                
                
                return rightCell;
            }
            
            
            break;
        }
            //此时是音频消息
        case -3:{
            //如果是自己发送的消息,调用leftCell
            if(!isMe){
                audioLeft *left = [tableView dequeueReusableCellWithIdentifier:leftAudio forIndexPath:indexPath];
                
                left.model  = self.currentUserArray[indexPath.row];
                left.backgroundColor =[UIColor colorWithRed:239/255.0f green:239/255.0f blue:244/255.0f alpha:1];
                //创建点击手势
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(playAction:)];
                left.leftBubble.userInteractionEnabled = YES ;
                left.leftVoice.userInteractionEnabled = YES;
                [left.leftBubble addGestureRecognizer:tap];
                [left.leftVoice addGestureRecognizer:tap];
                [left setSelectionStyle:UITableViewCellSelectionStyleNone];
                return left ;
            }
            //如果是收到的消息就以第二种格式
            else{
                rightAudioCell *right = [tableView dequeueReusableCellWithIdentifier:rightAudio forIndexPath:indexPath];
                right.model = self.currentUserArray[indexPath.row];
                right.backgroundColor = [UIColor colorWithRed:239/255.0f green:239/255.0f blue:244/255.0f alpha:1];
                //创建点击手势
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(playAction:)];
                right.rightBubble.userInteractionEnabled = YES ;
                [right.rightBubble addGestureRecognizer:tap];
                [right.rightVoice addGestureRecognizer:tap];
                right.rightVoice.userInteractionEnabled = YES;
                
                [right setSelectionStyle:UITableViewCellSelectionStyleNone];
                return right;
            }
            
            break;
        }
    }
    
    return nil;
}
#pragma mark -生命周期
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    NSLog(@"数组元素个数%ld",(unsigned long)self.currentUserArray.count);
    //将tableView滚动到最下面
    //此时如果数据源数组不为0的情况下
    if (self.currentUserArray.count > 0) {
        NSIndexPath *path = [NSIndexPath indexPathForRow:self.currentUserArray.count - 1 inSection:0];
        [_comTableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:NO];
        
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    
    //注册观察者
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardHide:) name:UIKeyboardWillHideNotification object:nil];
    
    AVUser *user = [AVUser currentUser];
    //创建一个client,用当前客户的手机号作为cliendId
    _client = [[AVIMClient defaultClient]initWithClientId:user.mobilePhoneNumber];
    
    
    self.client.delegate = self ;
    //一进去就直接打开连接
    [self.client openWithCallback:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            
            
        }else{
            NSLog(@"%@",error.localizedDescription);
        }
    }];
    [self loadHistory];
    
    //========================录音部分=======================
    [self createMicro];
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        //7.0第一次运行会提示，是否允许使用麦克风
        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *sessionError;
        //AVAudioSessionCategoryPlayAndRecord用于录音和播放
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if(session == nil)
            NSLog(@"Error creating session: %@", [sessionError description]);
        else
            [session setActive:YES error:nil];
    }
    //开始先隐藏
    _microPhoneView.alpha = 0 ;
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - 消息中心
- (void)keyBoardShow:(NSNotification *)notification{
    
    //获取键盘的frame
    CGRect rect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //拿到键盘的高度
    float keyboardHeight = rect.size.height;
    NSLog(@"%f", keyboardHeight);
    
    //让textfiled和tableView随着键盘上移
    [UIView animateWithDuration:0.3f animations:^{
        
        _tView.frame = CGRectMake(0, self.view.frame.size.height - 44 - keyboardHeight , _tView.frame.size.width, 44);
        
        _comTableView.frame = CGRectMake(0, 0 - keyboardHeight, _comTableView.frame.size.width, self.view.frame.size.height - 44);
        
    }];
    
    
}

- (void)hideKeyBoard{
    
    [_textView resignFirstResponder];
}

//键盘消失的响应
- (void)keyBoardHide:(NSNotification *)notification{
    
    [UIView animateWithDuration:0.3f animations:^{
        _tView.frame = CGRectMake(0, self.view.frame.size.height - 44 , LC_WIDTH, 44);
        _comTableView.frame = CGRectMake(0, 0, LC_WIDTH, self.view.frame.size.height - 44);
    }];
    
}
//销毁观察者
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark - 麦克风相关
//判断是否允许使用麦克风7.0新增的方法requestRecordPermission
-(BOOL)canRecord
{
    __block BOOL bCanRecord = YES;
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                if (granted) {
                    bCanRecord = YES;
                }
                else {
                    bCanRecord = NO;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[[UIAlertView alloc] initWithTitle:nil
                                                    message:@"app需要访问您的麦克风。\n请启用麦克风-设置/隐私/麦克风"
                                                   delegate:nil
                                          cancelButtonTitle:@"关闭"
                                          otherButtonTitles:nil] show];
                    });
                }
            }];
        }
    }
    
    return bCanRecord;
}

-(void)levelTimer:(NSTimer*)timer_
{
    //call to refresh meter values刷新平均和峰值功率,此计数是以对数刻度计量的,-160表示完全安静，0表示最大输入值
    [_recoder updateMeters];
    const double ALPHA = 0.05;
    double peakPowerForChannel = pow(10, (0.05 * [_recoder peakPowerForChannel:0]));
    _lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * _lowPassResults;
    
    
    
    if (_lowPassResults>=0.8) {
        _soundImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:7]];
    }else if(_lowPassResults>=0.7){
        _soundImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:6]];
    }else if(_lowPassResults>=0.6){
        _soundImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:5]];
    }else if(_lowPassResults>=0.5){
        _soundImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:4]];
    }else if(_lowPassResults>=0.4){
        _soundImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:3]];
    }else if(_lowPassResults>=0.3){
        _soundImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:2]];
    }else if(_lowPassResults>=0.2){
        _soundImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:1]];
    }else if(_lowPassResults>=0.1){
        _soundImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:0]];
    }else{
        _soundImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:0]];
    }
    
}
- (void)playAction:(UITapGestureRecognizer *)sender{
    NSError *playerError;
    UITableViewCell *cell =  (UITableViewCell *)[ [sender.view superview] superview] ;
    NSIndexPath *path = [_comTableView indexPathForCell:cell];
    comModel *model = self.currentUserArray[path.row];
    //拿到沙河路径
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    _playName =[NSString stringWithFormat:@"%@%@",docDir,model.audioUrl] ;
    NSLog(@"%@",_playName);
    //给audioSession赋予参数
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *sessionError = nil ;
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    [audioSession setActive:YES error:&sessionError];
    //(为了防止声音小)
    NSError *audioError = nil;
    BOOL success = [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&audioError];
    if(!success)
    {
        NSLog(@"error doing outputaudioportoverride - %@", [audioError localizedDescription]);
    }
    
    
    _player = nil;
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:_playName] error:&playerError];
    
    if (_player == nil)
    {
        NSLog(@"ERror creating player: %@", [playerError description]);
    }else{
        [_player play];
    }
    
    
}

@end